<template>
    <n-spin :show="loading">
        <n-space vertical :size="12">
            <n-space justify="space-between">
                <n-space></n-space>
                <n-space>
                    <n-form inline :model="param" :show-label="false" :show-feedback="false" ref="formRef">
                        <n-form-item label="城市">
                            <District v-model:code="area" style="width: 150px"></District>
                        </n-form-item>
                        <n-form-item>
                            <n-select
                                filterable
                                placeholder="请选择门店"
                                :disabled="mchs.length == 0"
                                :options="mchs"
                                style="width: 150px"
                                @update:value="(v:string) => {
                                param.pager.page = 1
                                param.query.mchid = v
                                execLoad()
                            }"
                            />
                        </n-form-item>
                        <n-form-item>
                            <n-select
                                v-model:value="param.query.state"
                                style="width: 120px"
                                placeholder="订单状态"
                                :options="[
                                    { label: '所有状态', value: 0 },
                                    { label: '等待支付', value: 1 },
                                    { label: '等待服务', value: 2 },
                                    { label: '租赁中', value: 3 },
                                    { label: '已完成交车', value: 4 },
                                    { label: '订单取消', value: 9 },
                                ]"
                            />
                        </n-form-item>
                        <n-form-item>
                            <n-input v-model:value="param.query.orderid" style="width: 150px" clearable placeholder="订单编号" />
                        </n-form-item>
                        <n-form-item>
                            <n-input v-model:value="param.query.name" style="width: 100px" clearable placeholder="客户名称" />
                        </n-form-item>
                        <n-form-item>
                            <n-input v-model:value="param.query.mob" style="width: 100px" clearable placeholder="客户手机" />
                        </n-form-item>
                        <n-form-item>
                            <n-tooltip trigger="hover">
                                <template #trigger>
                                    <n-date-picker v-model:value="dates" style="width: 250px" type="daterange" :update-value-on-close="true" />
                                </template>
                                下单时间
                            </n-tooltip>
                        </n-form-item>
                    </n-form>

                    <n-button @click="doQuery">
                        <template #icon>
                            <n-icon :component="YoutubeSearchedForRound" />
                        </template>
                    </n-button>
                </n-space>
            </n-space>
            <n-data-table
                :row-props="rowProps"
                striped
                size="large"
                type="selection"
                :checked-row-keys="srows"
                :max-height="height"
                :min-height="items.length > 0 ? height : 0"
                :row-key="(row:any) => row.id"
                @update:checked-row-keys="onCheckRow"
                :columns="columns"
                :data="items"
            />
            <n-space justify="end">
                <n-pagination show-size-picker :page="param.pager.page" :page-size="param.pager.size" :page-count="pager.all" :page-sizes="[10, 25, 50, 100]" @update:page="onChangePage" @update:page-size="onChangeSize">
                    <template #prefix="{}">当前 {{ pager.now }} / {{ pager.all }} 页，共 {{ pager.row }} 条数据</template>
                </n-pagination>
            </n-space>
        </n-space>
        <View :item="data" v-model:show="viewActive" v-if="viewActive"></View>
    </n-spin>
</template>

<script lang="ts" setup>
import { h, ref, computed, onActivated, watch } from 'vue'
import { NSpace, NText, NIcon, NButton, NTag } from 'naive-ui'
import { YoutubeSearchedForRound, InfoOutlined, EditNoteOutlined } from '@vicons/material'
import District from '@/comp/func/District.vue'

import { useStore } from '@/store'
import { Http, Filters } from '@/libs'

import View from './View.vue'

import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 导入本地化语言
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.locale('zh-cn')
dayjs.extend(customParseFormat)

const store = useStore()

const loading = computed(() => store.state.loading.flag)

const height = computed(() => store.state.browser.innerHeight - 310)

const area = ref<string | undefined>(undefined)

watch(area, (nv, _ov) => {
    execLoadMchs(nv)
    param.value.pager.page = 1
    param.value.query.area = nv + ''
    param.value.query.mchid = ''
})

const mchs = ref<any>([])

const execLoadMchs = (code: any) => {
    mchs.value = []
    Http.post('/ops/biz/merchant/info/query', {
        area: code + '',
        name: '',
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        mchs.value = resp.data.items.map((m: any) => {
            return {
                label: `[${m.id}] ${m.name} - ${m.full}`,
                value: m.id,
            }
        })
    })
    execLoad()
}
const rowProps = (row: any) => {
    return {
        style: 'cursor: pointer;',
        onClick: () => {
            data.value = row
            viewActive.value = true
        },
    }
}

const columns = [
    {
        title: '订单编号',
        key: 'id',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []

            comps[comps.length] = h(NText, { code: true }, { default: () => 'D' + row.id })
            if (row.state == 1) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'error' }, { default: () => '等待支付' })
            } else if (row.state == 2) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'warning' }, { default: () => '等待服务' })
            } else if (row.state == 3) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'success' }, { default: () => '租赁中' })
            } else if (row.state == 4) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false, type: 'info' }, { default: () => '已完成交车' })
            } else if (row.state == 9) {
                comps[comps.length] = h(NTag, { size: 'small', bordered: false }, { default: () => '订单取消' })
            }
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '出租门店',
        key: 'merchant',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => row.merchant.name })
            comps[comps.length] = h(NText, { code: true }, { default: () => 'S' + row.merchant.id })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '承租人',
        key: 'customer',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => row.customer.name })
            comps[comps.length] = h(NText, { code: true }, { default: () => row.customer.phone })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '租期时间',
        key: 'begin',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => '起：' + row.begin })
            comps[comps.length] = h('span', {}, { default: () => '至：' + row.close })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '车辆信息',
        key: 'car',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => row.car.cno + ' / ' + row.car.attr.color })
            comps[comps.length] = h('span', {}, { default: () => row.car.name })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '租金信息',
        key: 'rent',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => `租金：${Filters.money(row.rent.total)} / 押金：${Filters.money(row.deposit.total)}` })
            comps[comps.length] = h('span', {}, { default: () => `日租：${Filters.money(row.rent.day)} / 服务：${Filters.money(row.rent.srvs)}` })
            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '出租人/店',
        key: 'agency',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            if (row.agency.clerk) {
                comps[comps.length] = h('span', {}, { default: () => `${row.agency.clerk.name} / ${row.agency.merchant.name}` })
                comps[comps.length] = h('span', {}, { default: () => `佣金：${Filters.money(row.agency.total)}` })
            } else {
                comps[comps.length] = h('span', {}, { default: () => `门店订单` })
                comps[comps.length] = h('span', {}, { default: () => `无中介方` })
            }

            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
    {
        title: '订单时间',
        key: 'times',
        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => `下单：${row.times.create}` })
            if (row.state == 9) {
                comps[comps.length] = h('span', {}, { default: () => `取消：${row.times.cancel}` })
            } else if (row.state == 4) {
                comps[comps.length] = h('span', {}, { default: () => `完成：${row.times.finish}` })
            } else if (row.state == 3) {
                comps[comps.length] = h('span', {}, { default: () => `交车：${row.times.delivery}` })
            } else if (row.state == 2) {
                comps[comps.length] = h('span', {}, { default: () => `支付：${row.times.paid}` })
            }

            return h(NSpace, { wrap: false, vertical: true }, { default: () => comps })
        },
    },
]

const srows = ref<string[]>([])

const onCheckRow = (keys: string[]) => {
    srows.value = keys
}

const onChangeSize = (size: number) => {
    param.value.pager.page = 1
    param.value.pager.size = size
    execLoad()
}

const onChangePage = (page: number) => {
    param.value.pager.page = page
    execLoad()
}

const dates = ref<number[]>([dayjs().subtract(1, 'month').valueOf(), dayjs().valueOf()])
watch([dates, () => dates.value], (nv, _ov) => {
    let v = nv[0] as number[]
    param.value.query.begin = dayjs(v[0]).format('YYYY-MM-DD')
    param.value.query.close = dayjs(v[1]).format('YYYY-MM-DD')
})

const param = ref({
    query: {
        begin: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
        close: dayjs().format('YYYY-MM-DD'),
        mchid: '',
        carid: '',
        orderid: '',
        rentid: '',
        area: '',
        name: '',
        mob: '',
        state: 0,
    },
    pager: {
        page: 1,
        size: 10,
        time: new Date().getTime(),
    },
})

const pager = ref({
    now: 1,
    row: 0,
    all: 0,
    fms: 0,
})
const items = ref([])

const doQuery = () => {
    param.value.pager.page = 1
    execLoad()
}

const execLoad = () => {
    Http.post('/ops/biz/order/list', param.value).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        if (resp.data.pager.now == 1) {
            param.value.pager.time = resp.data.pager.fms
        }
        srows.value = []
        pager.value = resp.data.pager
        items.value = resp.data.items
    })
}

const data = ref<any>({})

const viewActive = ref(false)

onActivated(() => {
    execLoad()
})
</script>
